import com.alibaba.moco.RedisPoolInstance
import com.alibaba.moco.util.BaseTypeUtil
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.apache.commons.lang.StringUtils
import redis.clients.jedis.Jedis
import script.GlobalValues
import script.moco.dto.OrderDetailDTO
import script.moco.dto.OrderInfo
/**
 * 模拟 滴滴 登录授权认证
 * Created by wb-lj240895 on 2016/11/1.
 */
def excute(request){
    def params = request.getParameterMap();
    OrderIdRequest req = BaseTypeUtil.mapToBean(params, OrderIdRequest.class) as OrderIdRequest
    //TODO:判断必填参数
    if (true){
        Jedis redis = RedisPoolInstance.getRedisClient()
        String token = req.getAccess_token()
        System.out.println(token)
        //欢行异常判断
        def e = redis.hget(GlobalValues.KEY_EXCEPTION,"createId")
        if (!StringUtils.isBlank(e)) {
            def slurper = new JsonSlurper()
            def eJson = slurper.parseText(e)
            return eJson
        }
        if(token!=null/* && redis.exists(token)*/){
            //redis.del(token)
            def order_id = BigDecimal.valueOf(Math.abs(Math.random()+1)*10000000*10000000*10000000*1000000 -1).longValue();
            if (order_id<0) order_id = -order_id;
            System.out.println(order_id)
            def id = String.valueOf(order_id)
            //保存订单id
            OrderDetailDTO order = new OrderDetailDTO()
            order.setOrder(new OrderInfo())
            order.getOrder().setId(id)
            //redis.set(id,JsonOutput.toJson(order).toString())
            redis.set(GlobalValues.KEY_ORDER+id,JsonOutput.toJson(order).toString())
            redis.expire(GlobalValues.KEY_ORDER+id,GlobalValues.RIDES_EXPIRE)
            OrderIdResponse response = new OrderIdResponse();
            response.setErrno(0)
            response.setErrmsg("SUCCESS")
            Order data = new Order()
            data.setOrder_id(String.valueOf(order_id))
            response.setData(data)
            return JsonOutput.toJson(response)
        }else {
            OrderIdResponse response = new OrderIdResponse();
            response.setErrno(-1)
            response.setErrmsg("认证失败")
            return JsonOutput.toJson(response)
        }
    }else {
        return null
    }
}
public class OrderIdRequest{
    String  client_id	        //string	yes	申请应用时分配的AppKey
    String  access_token	    //string	yes	授权后的access token
    String     timestamp	        //int	yes	当前时间戳
    String  sign	            //string	yes	签名 详细算法参见 签名验证 章节
}
/**
 * "errno": 0,
 * "errmsg": "SUCCESS",
 * "data": {
 * "order_id": "4880109188406595918"
 * }
 */
public class OrderIdResponse{
    int     errno
    String  errmsg
    Order   data
}
public class Order{
    String order_id
}
